//
//  ActivityDetailViewController.swift
//  BUYOU
//
//  Created by tyuu on 2024/6/1.
//

import UIKit
import SnapKit

class ActivityDetailViewController: BaseViewController {

    var activity: RunActivity
    
    // 初始化时传入活动信息
    init(activity: RunActivity) {
        self.activity = activity
        super.init(nibName: nil, bundle: nil)
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }

    // 各种 UI 元素
    let scrollView = UIScrollView()
    let contentView = UIView()
    
    let posterImageView = UIImageView()
    let nameLabel = UILabel()
    let descriptionLabel = UILabel()
    let dateTimeLabel = UILabel()
    let locationLabel = UILabel()
    let distanceLabel = UILabel()
    let maxParticipantsLabel = UILabel()
    let currentParticipantsLabel = UILabel()
    let organizerLabel = UILabel()
    let registrationDeadlineLabel = UILabel()
    
    let participantsTitleLabel = UILabel()
    let participantsTableView = UITableView()
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        title = "活动详情"
        
        setupViews()
        setupConstraints()
        configureWithData()
        
        participantsTableView.dataSource = self
        participantsTableView.register(ParticipantTableViewCell.self, forCellReuseIdentifier: "ParticipantTableViewCell")
    }
    
    // 设置视图
    private func setupViews() {
        view.backgroundColor = .white
        
        nameLabel.font = UIFont.boldSystemFont(ofSize: 24)
        descriptionLabel.numberOfLines = 0
        dateTimeLabel.numberOfLines = 0
        locationLabel.numberOfLines = 0
        distanceLabel.numberOfLines = 0
        maxParticipantsLabel.numberOfLines = 0
        currentParticipantsLabel.numberOfLines = 0
        organizerLabel.numberOfLines = 0
        registrationDeadlineLabel.numberOfLines = 0
        participantsTitleLabel.font = UIFont.boldSystemFont(ofSize: 20)
        participantsTitleLabel.text = "参与者列表"
        
        posterImageView.contentMode = .scaleAspectFill
        posterImageView.layerCornerRadius = 1
        
        view.addSubview(scrollView)
        scrollView.addSubview(contentView)
        
        contentView.addSubview(posterImageView)
        contentView.addSubview(nameLabel)
        contentView.addSubview(descriptionLabel)
        contentView.addSubview(dateTimeLabel)
        contentView.addSubview(locationLabel)
        contentView.addSubview(distanceLabel)
        contentView.addSubview(maxParticipantsLabel)
        contentView.addSubview(currentParticipantsLabel)
        contentView.addSubview(organizerLabel)
        contentView.addSubview(registrationDeadlineLabel)
        contentView.addSubview(participantsTitleLabel)
        contentView.addSubview(participantsTableView)
    }
    
    // 设置约束
    private func setupConstraints() {
        scrollView.snp.makeConstraints { make in
            make.edges.equalTo(view)
        }
        
        contentView.snp.makeConstraints { make in
            make.edges.equalTo(scrollView)
            make.width.equalTo(scrollView)
        }
        
        posterImageView.snp.makeConstraints { make in
            make.top.equalTo(contentView).offset(16)
            make.centerX.equalTo(contentView)
            make.left.right.equalToSuperview()
            make.height.equalTo(300)
        }
        
        nameLabel.snp.makeConstraints { make in
            make.top.equalTo(posterImageView.snp.bottom).offset(16)
            make.left.right.equalTo(contentView).inset(16)
        }
        
        descriptionLabel.snp.makeConstraints { make in
            make.top.equalTo(nameLabel.snp.bottom).offset(8)
            make.left.right.equalTo(contentView).inset(16)
        }
        
        dateTimeLabel.snp.makeConstraints { make in
            make.top.equalTo(descriptionLabel.snp.bottom).offset(8)
            make.left.right.equalTo(contentView).inset(16)
        }
        
        locationLabel.snp.makeConstraints { make in
            make.top.equalTo(dateTimeLabel.snp.bottom).offset(8)
            make.left.right.equalTo(contentView).inset(16)
        }
        
        distanceLabel.snp.makeConstraints { make in
            make.top.equalTo(locationLabel.snp.bottom).offset(8)
            make.left.right.equalTo(contentView).inset(16)
        }
        
        maxParticipantsLabel.snp.makeConstraints { make in
            make.top.equalTo(distanceLabel.snp.bottom).offset(8)
            make.left.right.equalTo(contentView).inset(16)
        }
        
        currentParticipantsLabel.snp.makeConstraints { make in
            make.top.equalTo(maxParticipantsLabel.snp.bottom).offset(8)
            make.left.right.equalTo(contentView).inset(16)
        }
        
        organizerLabel.snp.makeConstraints { make in
            make.top.equalTo(currentParticipantsLabel.snp.bottom).offset(8)
            make.left.right.equalTo(contentView).inset(16)
        }
        
        registrationDeadlineLabel.snp.makeConstraints { make in
            make.top.equalTo(organizerLabel.snp.bottom).offset(8)
            make.left.right.equalTo(contentView).inset(16)
        }
        
        participantsTitleLabel.snp.makeConstraints { make in
            make.top.equalTo(registrationDeadlineLabel.snp.bottom).offset(16)
            make.left.right.equalTo(contentView).inset(16)
        }
        
        participantsTableView.snp.makeConstraints { make in
            make.top.equalTo(participantsTitleLabel.snp.bottom).offset(8)
            make.left.right.bottom.equalTo(contentView).inset(16)
            make.height.equalTo(300)  // 设置一个固定高度，可以根据实际需要调整
        }
        
        
        let button = UIButton(type: .system)
        button.setTitle("报名参加", for: .normal)
        button.setTitleColor(.white, for: .normal)
        button.backgroundColor = .blue
        button.layer.cornerRadius = 5
        button.clipsToBounds = true
        button.addTarget(self, action: #selector(showSignUpAlert), for: .touchUpInside)
        view.addSubview(button)
        
        button.snp.makeConstraints { make in
            make.bottom.equalTo(view.safeAreaLayoutGuide).inset(15)
            make.centerX.equalToSuperview()
            make.width.equalTo(300)
            make.height.equalTo(50)
        }
        
    }
    
    // 显示报名弹窗
    @objc
    func showSignUpAlert() {
           let alert = UIAlertController(title: "报名", message: "请输入姓名和电话号码", preferredStyle: .alert)
           
           alert.addTextField { textField in
               textField.placeholder = "姓名"
           }
           
           alert.addTextField { textField in
               textField.placeholder = "电话号码"
               textField.keyboardType = .phonePad
           }
           
           let submitAction = UIAlertAction(title: "提交", style: .default) { _ in
               guard let name = alert.textFields?[0].text, !name.isEmpty,
                     let phone = alert.textFields?[1].text, !phone.isEmpty else {
                   self.showErrorAlert()
                   return
               }
               self.showSuccessAlert(name: name)
           }
           
           let cancelAction = UIAlertAction(title: "取消", style: .cancel, handler: nil)
           
           alert.addAction(submitAction)
           alert.addAction(cancelAction)
           
           present(alert, animated: true, completion: nil)
       }
       
       // 显示错误弹窗
       private func showErrorAlert() {
           let alert = UIAlertController(title: "错误", message: "请填写所有字段", preferredStyle: .alert)
           alert.addAction(UIAlertAction(title: "确定", style: .default))
           present(alert, animated: true, completion: nil)
       }
       
       // 显示成功弹窗
       private func showSuccessAlert(name: String) {
           let alert = UIAlertController(title: "报名成功", message: "恭喜 \(name)，您已成功报名！请在规定时间参加。", preferredStyle: .alert)
           alert.addAction(UIAlertAction(title: "确定", style: .default))
           present(alert, animated: true, completion: nil)
       }
    
    // 配置数据
    private func configureWithData() {
   
        posterImageView.image = UIImage(named: activity.coverImageUrl)
        nameLabel.text = activity.name
        descriptionLabel.text = activity.description
        dateTimeLabel.text = "时间: \(activity.dateTime)"
        locationLabel.text = "地点: \(activity.location?.address ?? "")"
        distanceLabel.text = "距离: \(activity.distance) 公里"
        maxParticipantsLabel.text = "最大参与人数: \(activity.maxParticipants)"
        currentParticipantsLabel.text = "当前参与人数: \(activity.currentParticipants)"
        organizerLabel.text = "组织者: \(activity.organizer?.name ?? "")"
        registrationDeadlineLabel.text = "报名截止: \(activity.registrationDeadline)"
    }
}

extension ActivityDetailViewController: UITableViewDataSource {
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return activity.participants.count
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "ParticipantTableViewCell", for: indexPath) as! ParticipantTableViewCell
        let participant = activity.participants[indexPath.row]
        cell.configure(with: participant)
        return cell
    }
}

class ParticipantTableViewCell: UITableViewCell {
    
    let nameLabel = UILabel()
    let profileImageView = UIImageView()
    
    override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) {
        super.init(style: style, reuseIdentifier: reuseIdentifier)
        
        profileImageView.contentMode = .scaleAspectFit
        
        contentView.addSubview(nameLabel)
        contentView.addSubview(profileImageView)
        
        profileImageView.snp.makeConstraints { make in
            make.left.equalToSuperview().offset(16)
            make.centerY.equalToSuperview()
            make.width.height.equalTo(40)
        }
        
        nameLabel.snp.makeConstraints { make in
            make.left.equalTo(profileImageView.snp.right).offset(16)
            make.centerY.equalToSuperview()
            make.right.equalToSuperview().offset(-16)
        }
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    func configure(with participant: Participant) {
        nameLabel.text = participant.name
        profileImageView.image = UIImage(named: participant.profileImageUrl)
    }
}
